﻿using System;
using System.IO;

namespace UsersSettingsTool.Additional_Classes.TraceService
{
    public class TraceService : ITraceService
    {
        private readonly string _filePath;

        private readonly object _lockObject = new object();

        public TraceService()
        {
            _filePath = Environment.CurrentDirectory + @"\Log.txt";
        }

        private void CreateTraceFile(string path)
        {
            if (!File.Exists(path))
            {
                try
                {
                    var myFile = File.Create(path);
                    myFile.Close();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
            }
        }

        private void Write(string message)
        {
            try
            {
                lock (_lockObject)
                {
                    if (!File.Exists(_filePath))
                    {
                        CreateTraceFile(_filePath);
                    }

                    File.AppendAllText(_filePath, message + Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }

        public void WriteError(Exception ex)
        {
            Write(Environment.NewLine + DateTime.Now + ": The application terminated with an error.");
            Write("   Message: " + ex.Message);
            Write("   Stack Trace: " + ex.StackTrace);
            Write("   Inner Fault: " + (ex.InnerException != null ? WriteInnerFault(ex.InnerException) : "No Inner Fault."));
        }

        private string WriteInnerFault(Exception exception)
        {
            if (exception.InnerException == null)
                return "   " + exception.Message + Environment.NewLine;

            return exception.Message + Environment.NewLine + "   " + WriteInnerFault(exception.InnerException);

        }

        public void WriteInfo(string message)
        {
            Write(Environment.NewLine + DateTime.Now + " Information:");
            Write("   Message: " + message);
        }
    }
}
